package com.aps.server.service;

import com.aps.common.code.DistributedSnowflakeIdGenerator;
import com.aps.common.exception.SchedulingInvalidateException;
import com.aps.common.service.TestGenericService;
import com.aps.server.context.ValidateContext;
import com.aps.server.entity.ApsOrder;
import com.aps.server.entity.BasicProduct;
import com.aps.server.mapper.ApsOrderMapper;
import com.aps.server.mapper.BasicProductMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.BatchResult;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * APS订单服务类
 * 提供订单相关的业务逻辑处理
 */
@Slf4j
@Service
public class ApsOrderService extends TestGenericService {

    @Resource
    ApsOrderMapper apsOrderMapper;
    @Resource
    BasicProductMapper basicProductMapper;

    /**
     * 查询待排程订单列表
     * @return 待排程订单列表
     */
    public List<ApsOrder> getUnselectedOrders() {
        //获取租户号
        String currentTenantId = getCurrentTenantId();
        
        // 查询所有待排程订单（可根据实际需求添加更多筛选条件）
        LambdaQueryWrapper<ApsOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApsOrder::getTenantId, currentTenantId).eq(ApsOrder::getStatus,"0");
        // 可以添加其他筛选条件，例如：订单状态为待排程
        // queryWrapper.eq(ApsOrder::getStatus, "UNSCHEDULED");
        
        List<ApsOrder> orders = apsOrderMapper.selectList(queryWrapper);
        log.info("查询待排程订单数量：{}", orders != null ? orders.size() : 0);
        
        return orders != null ? orders : new ArrayList<>();
    }


    public List<ApsOrder> selectedOrder(List<ApsOrder> apsOrders) {
        //获取租户号
        String currentTenantId = getCurrentTenantId();
        apsOrders.forEach(apsOrder -> {
            //赋值 租户号
            apsOrder.setTenantId(currentTenantId);
            //赋值 aps内部订单编号 （对应 工单编号字段）
            apsOrder.setApsOrderCode("ORDER_APS_" + DistributedSnowflakeIdGenerator.generate20DigitId());
            //赋值待计划状态
            apsOrder.setStatus("0");
        });
        List<BatchResult> insert = apsOrderMapper.insert(apsOrders,1000);
        log.info("新增订单数量：{}", insert.size());
        return apsOrders;
    }

    public List<ApsOrder> queryOrders(List<String> apsOrderCodes) {
        if(CollectionUtils.isEmpty(apsOrderCodes)){
            return Collections.emptyList();
        }
        LambdaQueryWrapper<ApsOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ApsOrder::getApsOrderCode, apsOrderCodes)
                .eq(ApsOrder::getTenantId, getCurrentTenantId())
                .eq(ApsOrder::getStatus,"0");
        return apsOrderMapper.selectList(queryWrapper);


    }


    /**
     * 按照产品编码查询对应产品是否有效
     *
     * 返回不存在的产品编码 （无效数据）
     */
    public void orderCheck(List<ApsOrder> orders , ValidateContext context) {
        productCodeCheck(orders.stream().map(ApsOrder::getProductCode).collect(Collectors.toList()), context);
    }

    private void productCodeCheck(List<String> productCodes , ValidateContext context) {
        LambdaQueryWrapper<BasicProduct> productQ = new LambdaQueryWrapper<BasicProduct>()
                .eq(BasicProduct::getTenantId, getCurrentTenantId())
                .in(BasicProduct::getProductCode, productCodes);
        List<BasicProduct> basicProducts = basicProductMapper.selectList(productQ);
        context.setProducts(basicProducts);
    }

}